import vueMain from "@/main.js";
import store from "@/store/index";
import {
	setMute,
	getMute
} from "@/services/chat";
import {
	getUserInfo,
	getGroupInfo,
	getGroupMemberInfo,
	getBatchUserInfo,
	formatUserName,
	disposeReceivedMsg,
	getOlUsersInfo,
	getSingleUserInfo,
	offlineOperate
} from "./index";
import {
	queryGroupList
} from "@/services/group";
import {
	getDefaultColor
} from "@/utils/index";



/**
 * getChatList 聊天列表
 * @param {*} startTime 获取会话列表所使用的时间戳，需要精确到毫秒，0表示当前时间
 * @param {*} count 想要获取的会话列表数量，默认值 300，最大值 1000
 * @param {*} order 会话排序方式: 0按会话生成时间倒序排列，即获取早于 startTime 生成的会话列表,1按会话生成时间正序排列，即获取晚于 startTime 生成的会话列表
 */
const getChatList = async (startTime = 0, count = 300, order = 0) => {
	let chatListData = [];
	// 缓存中是否存在聊天数据
	if (store.state.chatList.length > 0) {
		chatListData = store.state.chatList.slice(0, count);
		getRongIMChatList(startTime, count, order).then(res => {
			uni.stopPullDownRefresh();
			store.commit('SET_PAGE_CHAT_LIST', res)
			console.log(res, "xnxx");
		})
	} else {
		chatListData = await getRongIMChatList(startTime, count, order);
		uni.stopPullDownRefresh();
		store.commit('SET_PAGE_CHAT_LIST', chatListData)
		console.log(chatListData, "xnxx");
	}
	return chatListData;
};

/**
 * 定义特殊群聊的moduleType，交易部分以订单作为一个群聊，故不需要处理
 * 1：交友
 * 2：交易
 * 3：悬赏
 * 4：招聘
 * 5：信息发布
 * 6：客服
 */
const specialRoom = [1, 3, 4, 5, 6]

/**
 * getRongIMChatList 获取融云返回的聊天列表
 * @param {*} startTime 获取会话列表所使用的时间戳，需要精确到毫秒，0表示当前时间
 * @param {*} count 想要获取的会话列表数量，默认值 300，最大值 1000
 * @param {*} order 会话排序方式: 0按会话生成时间倒序排列，即获取早于 startTime 生成的会话列表,1按会话生成时间正序排列，即获取晚于 startTime 生成的会话列表
 */
const getRongIMChatList = async (startTime = 0, count = 300, order = 0) => {
	let chatListData = [];
	const chatParam = {
		startTime,
		count,
		order,
	};
	const res = await vueMain.$RongIMLib.getConversationList(chatParam);
	if (res.code === 0) {
		const chatList = res.data;
		console.log('会话原有信息', chatList);
		if (chatList.length == 0) {
			store.commit("SET_CHAT_LIST", []);
			return;
		}

		const groupResp = await queryGroupList({
			pageNum: 1,
			pageSize: 999,
			userId: store.state.userInfo.userId
			// groupId: data.targetId
		})
		const friendIds = []
		chatList.forEach((t) => {
			if (t.conversationType === 1) {
				friendIds.push(t.targetId)
			}
		})
		const privateList = await getOlUsersInfo(friendIds)

		const groupList = groupResp.result.rows || []

		for (let i = 0; i < chatList.length; i++) {
			let info = {};
			const data = chatList[i];
			// conversationType: 1 私聊, 3 群聊
			if (data.conversationType == 1) {
				info = privateList.find(
					(o) => o.userId.toString() === data.targetId.toString()
				)
				if (info) {
					info.moduleType = 0
				}
			} else if (data.conversationType == 6) {
				info.commentLast = 'chat.Service-Messages'
				info.avatarCompress = require('@/static/image/chat/system.png')
				if (info) {
					info.moduleType = 0
				}
			} else if (data.conversationType == 3) {
				// info = getGroupInfo(data.targetId);
				// console.log('info', info);
				// if (!info) {
				const group = groupList.find(
					(o) => o.groupId.toString() === data.targetId.toString()
				)
				// console.log('group', group, data.targetId, groupList);
				if (group) {
					// 交友部分，显示名称逻辑，根据userId进行区分 -- start
					if (
						specialRoom.includes(group.moduleType) &&
						group.userId === store.state.userInfo.userId
					) {
						group.myName = group.jyRemark || 'OMLOOKER'
					} else if (
						specialRoom.includes(group.moduleType) &&
						group.userId !== store.state.userInfo.userId
					) {
						group.myName = group.groupName
						group.groupName = group.jyRemark || 'OMLOOKER'
						group.avatarCompress = group.jyAvatar || (group.moduleType == 1 ?
							'http://www.omlook.com/imol/default_male.png' : 'https://www.omlook.com/imol/account.png')
					}
					// 交友部分，显示名称逻辑，根据userId进行区分 -- end
					group.defaultName = group.groupName.slice(0, 1)
					group.showAvatar = group.avatar
					group.defaultColor = getDefaultColor(group.avatarColorCode)
					info = group
					// group.defaultName = group.groupName.slice(0, 1);
					// group.showAvatar = group.avatar;
					// group.avatarColorCode = group.avatarColorCode;
					// group.defaultColor = getDefaultColor(group.avatarColorCode);
					// info = group;
					const index = store.state.groupList.findIndex(t => t.groupId == info.groupId)
					if (index != -1) {
						store.state.groupList[index] = info;
					} else {
						store.state.groupList.push(info);
					}
					// }

					// getHistoryMessages(data.targetId, data.conversationType);
				}
			}

			chatListData.push({
				...data,
				info: info,
			});
		}

		const chatListFull = await getUnreadMessage(chatListData);
		console.log('处理后的会话列表', chatListFull);
		store.commit("SET_CHAT_LIST", chatListFull);
		store.commit("SET_PAGE_CHAT_LIST", chatListFull);
	} else {
		console.log(res, res.code, res.msg);
	}
	uni.hideLoading();
	return chatListData;
};

/**
 * 获取会话未读数
 */
const getUnreadMessage = async (chatList) => {
	const conversationTypes = [
		vueMain.$RongIMLib.ConversationType.PRIVATE,
		vueMain.$RongIMLib.ConversationType.GROUP,
	];
	const res = await vueMain.$RongIMLib.getUnreadConversationList(
		conversationTypes
	);
	let newDataList = [];
	if (res.code === 0) {
		newDataList = !res.data.length ?
			chatList :
			chatList.map((element) => {
				const index = chatList.findIndex(
					(item) => item.targetId === element.targetId
				);
				return {
					...element,
					unreadMentionedCount: index === -1 ? 0 : element.unreadMentionedCount,
					unreadMessageCount: index === -1 ? 0 : element.unreadMessageCount,
				};
			});
	} else {
		console.log(res.code, res.msg);
	}
	return newDataList;
};

/**
 * getHistoryMessages 获取会话历史
 * @param {*} targetId
 * @param {*} conversationType 1 私聊， 3 群聊
 */
const getHistoryMessages = async (targetId, conversationType) => {
	// const totalList = await getAllRongHistoryMessages(targetId, conversationType)
	// console.log('----totalList', totalList);
	// let chatInfoList = []
	// console.log(store.state.privateChatInfo[targetId])
	// if (conversationType === 1) {
	//   // chatInfoList = store.state.privateChatInfo[targetId]
	//   //   ? store.state.privateChatInfo[targetId]
	//   //   : await getRongHistoryMessages(targetId, conversationType)
	//   chatInfoList = await getRongHistoryMessages(targetId, conversationType)
	//   return chatInfoList
	// } else if (conversationType === 3) {
	//   // chatInfoList =
	//   //   store.state.groupChatInfo[targetId] ||
	//   //   (await getRongHistoryMessages(targetId, conversationType))
	//   chatInfoList = await getRongHistoryMessages(targetId, conversationType)
	// }
	const chatInfoList = await getRongHistoryMessages(targetId, conversationType)
	return chatInfoList;
};

// /**
//  * 获取融云指定会话所有聊天记录
//  * @param {*} targetId
//  * @param {*} conversationType 1 私聊， 3 群聊
//  */
// const getAllRongHistoryMessages = async (targetId, conversationType, pageNo = 1, timestamp = 0, totalList = []) => {
//   const list = await getRongHistoryMessages(targetId, conversationType, timestamp)
//   totalList = totalList.concat([...list])
//   console.log('totalList', totalList);
//   if (list.length == 20) {
//     pageNo++
//     timestamp = list[19].sentTime
//     await getAllRongHistoryMessages(targetId, conversationType, pageNo, timestamp, totalList)
//   }
//   console.log('----------------------------totalList---------------------', totalList);
//   return totalList
// }

/**
 * getRongHistoryMessages 获取融云会话历史
 * @param {*} targetId
 * @param {*} conversationType 1 私聊， 3 群聊
 */
const getRongHistoryMessages = async (
	targetId,
	conversationType,
	timestamp = 0,
) => {
	let chatInfoList = [];
	const conversation = {
		targetId: targetId,
		conversationType: Number(conversationType)
	};
	// 从当前时间开始向前查询
	const option = {
		timestamp,
		count: 20,
		order: 0,
	};
	const res = await vueMain.$RongIMLib.getHistoryMessages(conversation, option);
	console.log('conversationType', conversationType);
	if (res.code === 0) {

		if (conversationType == 1) {
			chatInfoList = res.data.list;
			// const privateChatInfo = store.state.privateChatInfo;
			// privateChatInfo[targetId] = timestamp
			//   ? chatInfoList.concat([...privateChatInfo[targetId]])
			//   : chatInfoList;
			// console.log("SET_PRIVATE_CHAT_INFO", privateChatInfo);
			// store.commit("SET_PRIVATE_CHAT_INFO", privateChatInfo);
		} else if (conversationType == 6) {
			chatInfoList = res.data.list;
		} else {
			let msgIds = []
			res.data.list.forEach((item) => {
				msgIds.push(item.senderUserId)
			})
			msgIds = [...new Set(msgIds)]
			const privateList = await getOlUsersInfo(msgIds)

			if (privateList && privateList.length > 0) {
				for (let i = 0; i < privateList.length; i++) {
					const element = privateList[i]
					const userInfo = element
					let showUserName = ''
					if (userInfo.userId == store.state.userId) {
						showUserName = formatUserName(store.state.userInfo)
					} else {
						showUserName = formatUserName(userInfo)
					}
					const data = {
						...element,
						showUserName,
						showUserAvatar: userInfo.avatar,
						avatarColorCode: userInfo.avatarColorCode,
						defaultColor: getDefaultColor(userInfo.avatarColorCode)
					}
					// data.defaultName = data.showUserName.slice(0, 1)
					data.defaultName = data.showUserName
					privateList[i] = data
				}
			}
			// const groupMemberInfo = await getGroupMemberInfo(targetId);
			chatInfoList = res.data.list.map((item) => {
				const index = privateList.findIndex(
					(e) => Number(e.userId) === Number(item.senderUserId)
				);
				return {
					...item,
					info: privateList[index],
				};
			});
			// const groupChatInfo = store.state.groupChatInfo

			// groupChatInfo[targetId] = timestamp
			//   ? chatInfoList.concat([...groupChatInfo[targetId]])
			//   : chatInfoList
			// groupChatInfo[targetId] = chatInfoList
			// console.log(groupChatInfo, "groupChatInfo")
			// store.commit("SET_GROUP_CHAT_INFO", groupChatInfo)
		}
	} else {
		console.log(res.code, res.msg);
	}
	return chatInfoList;
};

/**
 * 监听消息来了，统一更新缓存
 */
const allWatchMessages = async (messages) => {
	const msg = messages.messages;
	console.log("消息来了", msg);
	if (msg.length > 20) {
		getChatList()
		return
	}

	for (let i = 0; i < msg.length; i++) {

		const msgItem = msg[i];

		// 如果是视频类型的消息,则不做处理
		if (msgItem.messageType.indexOf('RC:VC') !== -1) {
			return
		}
		/**
		 *  此处判断是否挤号信息
		 */
		if (msgItem.targetId === '1640654047285551105' && msgItem.conversationType == 1) {
			if (msgItem.content.extra == 403) {
				offlineOperate()
			}
			return
		}

		disposeReceivedMsg(msgItem)
		if (msgItem.conversationType == 1) {
			const privateChatInfo = store.state.privateChatInfo;
			privateChatInfo[msgItem.targetId] = [msgItem]
			console.log("SET_PRIVATE_CHAT_INFO", privateChatInfo);
			store.commit("SET_PRIVATE_CHAT_INFO", privateChatInfo);
			// await getRongHistoryMessages(msgItem.targetId, 1, 'new');
		} else if (msgItem.conversationType == 6) {
			// const privateChatInfo = store.state.privateChatInfo;
			// privateChatInfo[msgItem.targetId] = [msgItem]
			// store.commit("SET_PRIVATE_CHAT_INFO", privateChatInfo);
			// await getRongHistoryMessages(msgItem.targetId, 1, 'new');
		} else {
			const groupMemberInfo = await getSingleUserInfo(msgItem.senderUserId)

			// const groupMemberInfo = await getGroupMemberInfo(msgItem.targetId);
			// const index = groupMemberInfo.findIndex(
			// 	(e) => Number(e.userId) === Number(msgItem.senderUserId)
			// );
			// msgItem.info = groupMemberInfo[index]
			msgItem.info = groupMemberInfo
			msgItem.info.userVo = {
				...groupMemberInfo
			}
			console.log(msgItem, 'groupMemberInfogroupMemberInfogroupMemberInfo')
			const groupChatInfo = store.state.groupChatInfo

			groupChatInfo[msgItem.targetId] = [msgItem]
			console.log(groupChatInfo, "groupChatInfo")
			store.commit("SET_GROUP_CHAT_INFO", groupChatInfo)
			// await getRongHistoryMessages(msgItem.targetId, 3, 'new');
		}
	}
	// await getChatList();
	// 5.1.2 版本开始，事件回调中会引起中断的 code 状态码
}
/**
 * 清除会话未读数
 * @param {*} targetId
 * @param {*} conversationType
 */
const clearMessageUnreadStatus = (targetId, conversationType) => {
	const conversation = {
		targetId: targetId,
		conversationType: Number(conversationType)
	};
	vueMain.$RongIMLib.clearMessagesUnreadStatus(conversation).then((res) => {
		if (res.code === 0) {
			const chatList = store.state.chatList;
			const index = chatList.findIndex(
				(item) =>
				item.targetId == targetId && item.conversationType == conversationType
			);

			chatList[index].unreadMentionedCount = 0;
			chatList[index].unreadMessageCount = 0;
			chatList[index].hasMentioned = false;
			store.commit("SET_CHAT_LIST", chatList);
		} else {
			console.log(res.code, res.msg);
		}
	});
};

/**
 * 移除消息监听
 */
const removeWatchMessage = () => {
	vueMain.$RongIMLib.removeEventListener(
		vueMain.$RongIMLib.Events.MESSAGES,
		(evt) => {
			console.log('取消监听》》》》', evt)
		}
	)
	vueMain.$RongIMLib.disconnect().then(() => {
		// uni.reLaunch({
		// 	url: "/pages/login/Login",
		// });
	})
}



/**
 * 消息免打扰
 * @param {*} targetId
 * @param {*} type
 */
const muteChange = async (options) => {
	const resp = await setMute({
		...options
	});
	if (!resp.success) return;
	delete options.type;
	getConversationNoticeStatus(options);
};
/**
 * 获取免打扰级别
 * @param {*} targetId
 */
const getConversationNoticeStatus = async (options) => {
	const resp = await getMute({
		...options
	});
	if (!resp.success) return;
	const chatList = store.state.chatList;
	const index = chatList.findIndex((item) => item.targetId == options.targetId && item.conversationType == options
		.conversationType);
	console.log(chatList[index], '获取免打扰级别', index)
	if (index > -1) {
		if (resp.result.data != null) {
			chatList[index].notificationLevel = resp.result.data == 0 ? -1 : 5;
			store.commit("SET_CHAT_LIST", chatList);
		}
	}
	return resp.result;
	// const conversationType = vueMain.$RongIMLib.ConversationType.GROUP;
	// vueMain.$RongIMLib
	//   .getConversationNotificationLevel({
	//     conversationType,
	//     targetId,
	//   })
	//   .then(({ code, data }) => {
	//     fn(data);
	//   });
};
/**
 * 搜索消息
 * @param {*} targetId //会话 ID
 * @param {*} conversation //会话
 * @param {*} keyword //关键字
 * @param {*} startTime //搜索时间, 搜索该时间之前的消息
 * @param {*} count //获取的数量
 */
const searchConversation = (targetId, fn) => {
	const conversation = {
		conversationType: vueMain.$RongIMLib.ConversationType.PRIVATE,
		targetId: targetId,
		channelId: "",
	};
	const keyword = "搜索关键字";
	const startTime = Date.now();
	const count = 10;

	vueMain.$RongIMLib.electronExtension
		.searchMessages(conversation, keyword, startTime, count)
		.then((res) => {
			if (res.code === 0) {
				console.log(res.code, res.data);
			} else {
				console.log(res.code, res.msg);
			}
		})
		.catch((error) => {
			console.log(error);
		});
};
/**
 * 获取历史消息
 * @param {*} targetId //会话 ID
 * @param {*} conversation //会话
 * @param {*} startTime //搜索时间, 搜索该时间之前的消息
 * @param {*} count //获取的数量
 * @param {*} order //0表示降序 1表示升序
 */
const historyMessages = (targetId, fn) => {
	const conversation = {
		conversationType: vueMain.$RongIMLib.ConversationType.PRIVATE,
		targetId: targetId,
	};
	const options = {
		order: 1,
		timestamp: Date.now(),
		count: 10,
	};
	vueMain.$RongIMLib
		.getHistoryMessages(conversation, options)
		.then((res) => {
			if (res.code === 0) {
				fn && fn(res.data.list);
				console.log(res.data.list, "22222");
				console.log(res.data.hasMore);
			} else {
				console.log(res.code, res.msg);
			}
		})
		.catch((error) => {
			console.log(error);
		});
};
export {
	getChatList,
	getHistoryMessages,
	getRongHistoryMessages,
	allWatchMessages,
	getUnreadMessage,
	clearMessageUnreadStatus,
	muteChange,
	getConversationNoticeStatus,
	getRongIMChatList,
	searchConversation,
	historyMessages,
	removeWatchMessage
};